package com.teemor.tim.processor.message;

import com.teemor.tim.bean.result.message.MessageRecordResult;
import com.teemor.tim.processor.MessageProcessor;
import com.teemor.tim.model.message.StoreMessageWrapper;
import com.teemor.tim.model.search.MessageRecordSearch;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ename zhoulk
 * @cname 周李科
 * @date 2020/12/18 15:22
 */
@Component
public class MemoryMessageProcessor implements MessageProcessor {

    private List<StoreMessageWrapper> messageRespoty = new ArrayList<>();

    @Override
    public void storeMessage(StoreMessageWrapper messageWrapper) {
        messageRespoty.add(messageWrapper);
    }

    @Override
    public List<MessageRecordResult> getMessages(MessageRecordSearch search) {
        List<StoreMessageWrapper> messageWrappers = messageRespoty.stream().filter(messageWrapper -> {
            boolean flag = true;
            if (StringUtils.isNotBlank(search.getFromUser())) {
                flag = search.getFromUser().equals(messageWrapper.getFromAccount());
            }
            if (StringUtils.isNotBlank(search.getToUser())) {
                flag = search.getToUser().equals(messageWrapper.getToAccount()) || flag;
            }
            return flag;
        }).collect(Collectors.toList());

        List<MessageRecordResult> messageRecordResults = new ArrayList<>();
        messageWrappers.forEach(messageWrapper -> {
            MessageRecordResult result = new MessageRecordResult();
            String id = "C2C"+ search.getCsId() +"-" +messageWrapper.getMsgSeq() + "-" + messageWrapper.getMsgRandom();
            result.setID(id);
            result.setClientSequence(messageWrapper.getMsgSeq());
            result.setFlow(search.getFromUser().equals(messageWrapper.getFromAccount()) ? "in" : "out");
            result.setConversationType("C2C");
            result.setConversationID("C2C" + messageWrapper.getFromAccount());
            result.setFrom(messageWrapper.getFromAccount());
            result.setTo(messageWrapper.getToAccount());
            result.setPayload(messageWrapper.getMessageModel().get(0).getMessage());
            result.setType(messageWrapper.getMessageModel().get(0).getMsgType());
            result.setRandom(messageWrapper.getMsgRandom());
            result.setTime(messageWrapper.getMsgTime());
            messageRecordResults.add(result);
        });

        return messageRecordResults;
    }
}
